/*
 * Created on 2009-8-23
 * Last modified on 2009-8-23
 * Powered by YeQiangWei.com
 */
package com.yeqiangwei.commons.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 
 * @author aroot
 *
 */
public class HttpSessionUtils {
	
	private static final Log log = LogFactory.getLog(HttpSessionUtils.class);
	
	public static void setAttribute(HttpServletRequest request, 
			String name, Object value) 
	{	if(request == null || request.getSession(true) == null){
			log.warn("...... HttpSessionUtils#setAttribute(...), " +
					"request == null || request.getSession(true) == null");
			return ;
		}
		request.getSession(true).setAttribute(name, value);
	}

	public static void removeAttribute(HttpServletRequest request,
			String name) 
	{
		if (request != null && request.getSession() != null) {
			request.getSession().removeAttribute(name);
		} else {
			log.warn("HttpServletRequest is null");
		}
	}
	
	
	public static String getString(HttpServletRequest request, String name,
			String def) 
	{
		if(request == null){
			return def;
		}
		HttpSession httpsession = request.getSession(true);
		if (httpsession != null && httpsession.getAttribute(name) != null) 
		{
			return String.valueOf(httpsession.getAttribute(name));
		}
		return def;
	}
	
	public static Integer getInteger(HttpServletRequest request,
			String name, Integer def) 
	{
		return TypeChange.stringToInteger(getString(request, 
				name, null), def);
	}

	public static Boolean getBoolean(HttpServletRequest request,
			String name, Boolean def) 
	{
		if(request == null){
			return def;
		}
		HttpSession httpsession = request.getSession(true);
		if (httpsession != null) {
			return TypeChange.objectToBoolean(httpsession.getAttribute(name), def);
		}
		return def;
	}
	
	@SuppressWarnings("unchecked")
	public static <Obj> Obj getObject(HttpServletRequest request, 
			String name, Obj val) 
	{
		if (request != null && request.getSession() != null 
				&& request.getSession().getAttribute(name) != null) 
		{
			return (Obj) request.getSession().getAttribute(name);
		}
		return val;
	}
	
}
